<template>
  <view class="container">
    <!-- AI对话区域 -->
    <scroll-view 
      class="chat-container" 
      scroll-y="true" 
      :scroll-top="scrollTop"
    >
      <view 
        v-for="(msg, index) in chatMessages" 
        :key="index" 
        :class="['message', msg.role === 'user' ? 'user-message' : 'ai-message']"
      >
        <view class="message-content">{{ msg.content }}</view>
        <!-- 为AI回复添加"用作笔记"按钮 -->
        <view v-if="msg.role === 'assistant'" class="message-actions">
          <button class="action-btn" @tap="useAsNote(msg)">用作笔记</button>
        </view>
      </view>
    </scroll-view>

    <!-- 笔记编辑区域 -->
    <view v-if="showNoteEditor" class="note-editor">
      <view class="editor-header">
        <text>编辑笔记</text>
        <text class="close-btn" @tap="closeEditor">×</text>
      </view>
      
      <input 
        v-model="noteForm.title"
        class="note-title"
        placeholder="请输入标题"
      />
      
      <textarea 
        v-model="noteForm.content"
        class="note-content"
        placeholder="请输入正文"
      />
      
      <!-- 图片预览区 -->
      <view class="image-preview" v-if="noteForm.images.length > 0">
        <view v-for="(img, index) in noteForm.images" :key="index" class="image-item">
          <image :src="img" mode="aspectFill" />
          <text class="delete-btn" @tap="deleteImage(index)">×</text>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="note-actions">
        <button class="action-btn upload" @tap="chooseImage">添加图片</button>
        <button class="action-btn publish" @tap="jumpToXiaohongshuApp">发布到小红书</button>
      </view>
    </view>

    <!-- 图片上传预览区 -->
    <view class="image-preview" v-if="tempImages.length > 0">
      <image 
        v-for="(img, index) in tempImages" 
        :key="index" 
        :src="img" 
        class="preview-img"
        @tap="previewImage(img)"
      />
    </view>

    <!-- 输入区域 -->
    <view class="input-area">
      <!-- 图片上传按钮 -->
      <view class="upload-btn" @tap="chooseImage">
        <text class="iconfont">+</text>
      </view>

      <!-- 文本输入框 -->
      <input 
        v-model="inputMessage"
        class="text-input"
        placeholder="请输入您想宣传的农产品..."
        :disabled="isRecording"
      />

      <!-- 语音输入按钮 -->
      <view 
        class="voice-btn"
        @touchstart="startRecording"
        @touchend="stopRecording"
        @touchcancel="cancelRecording"
      >
        <text class="iconfont">🎤</text>
      </view>

      <!-- 发送按钮 -->
      <view class="send-btn" @tap="sendMessage">
        <text class="iconfont">发送</text>
      </view>
    </view>
  </view>
</template>

<script>
const recorderManager = uni.getRecorderManager();

export default {
  data() {
    return {
      chatMessages: [],
      inputMessage: '',
      tempImages: [],
      isRecording: false,
      scrollTop: 0,
      chatId: null, // 当前对话ID
      userId: null,  // 当前用户ID
      showNoteEditor: false,
      noteForm: {
        title: '',
        content: '',
        images: []
      }
    }
  },

  async onLoad() {
    this.initRecorder();
    // 获取用户信息
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userId = userInfo.userId;
      // 加载最近的对话
      await this.loadRecentChat();
    } else {
      // 未登录则跳转到登录页
      wx.switchTab({
        url: '/pages/user/user', // 确保这里是正确的 TabBar 页面路径
        success: () => {
          console.log('成功跳转到 TabBar 页面');
        },
        fail: (err) => {
          console.error('跳转失败:', err);
        }
      });
    }
  },

  methods: {
    // 初始化录音管理器
    initRecorder() {
      recorderManager.onStop(async (res) => {
        if (this.isRecording) {
          this.isRecording = false;
          // 调用语音识别API
          try {
            const result = await this.speechToText(res.tempFilePath);
            this.inputMessage = result;
          } catch (error) {
            uni.showToast({
              title: '语音识别失败',
              icon: 'none'
            });
          }
        }
      });
    },

    // 开始录音
    startRecording() {
      this.isRecording = true;
      recorderManager.start({
        duration: 60000, // 最长录音时间
        format: 'mp3'
      });
      uni.showToast({
        title: '开始录音',
        icon: 'none'
      });
    },

    // 停止录音
    stopRecording() {
      recorderManager.stop();
      uni.showToast({
        title: '录音结束',
        icon: 'none'
      });
    },

    // 取消录音
    cancelRecording() {
      this.isRecording = false;
      recorderManager.stop();
    },

    // 选择图片
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 9,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        });
        
        // 上传图片到云存储
        for (let tempFilePath of res.tempFilePaths) {
          const uploadRes = await this.uploadFile(tempFilePath);
          this.tempImages.push(uploadRes.fileID);
        }
      } catch (error) {
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    },

    // 预览图片
    previewImage(current) {
      uni.previewImage({
        urls: this.tempImages,
        current
      });
    },

    // 加载最近的对话
    async loadRecentChat() {
      try {
        const result = await uniCloud.callFunction({
          name: 'getRecentChat',
          data: {
            userId: this.userId
          }
        });

        if (result.result.code === 0 && result.result.data) {
          this.chatId = result.result.data._id;
          this.chatMessages = result.result.data.messages;
          this.$nextTick(() => {
            this.scrollTop = 9999;
          });
        }
      } catch (error) {
        console.error('加载对话失败:', error);
      }
    },

    // 发送消息
    async sendMessage() {
      if (!this.inputMessage && this.tempImages.length === 0) {
        return;
      }

      // 构建用户消息
      const userMessage = {
        role: 'user',
        content: this.inputMessage,
        images: this.tempImages
      };

      // 添加到消息列表
      this.chatMessages.push(userMessage);

      // 调用AI接口
      try {
        const result = await uniCloud.callFunction({
          name: 'aiChat',
          data: {
            message: userMessage,
            userId: this.userId,
            chatId: this.chatId
          }
        });

        if (result.result.code === 0) {
          // 添加AI回复
          this.chatMessages.push({
            role: 'assistant',
            content: result.result.response
          });

          // 如果是新对话，保存对话ID
          if (!this.chatId && result.result.chatId) {
            this.chatId = result.result.chatId;
          }

          // 存储对话到云数据库
          await this.saveChatToDatabase(userMessage, {
            role: 'assistant',
            content: result.result.response
          });
        } else {
          throw new Error(result.result.message);
        }
      } catch (error) {
        uni.showToast({
          title: '获取AI回复失败: ' + error.message,
          icon: 'none'
        });
      }

      // 清空输入
      this.inputMessage = '';
      this.tempImages = [];
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollTop = 9999;
      });
    },

    // 上传文件到云存储
    async uploadFile(tempFilePath) {
      return await uniCloud.uploadFile({
        filePath: tempFilePath,
        cloudPath: `publish/${Date.now()}-${Math.random().toString(36).slice(-6)}.png`
      });
    },

    // 语音转文字
    async speechToText(audioFile) {
      // 调用语音识别云函数
      const result = await uniCloud.callFunction({
        name: 'speechToText',
        data: {
          audioFile
        }
      });
      return result.result.text;
    },

    // 使用AI回复作为笔记
    useAsNote(message) {
      this.showNoteEditor = true;
      this.noteForm.content = message.content;
      // 如果消息中包含图片，也添加到笔记中
      if (message.images && message.images.length > 0) {
        this.noteForm.images = [...message.images];
      }
    },

    // 关闭编辑器
    closeEditor() {
      this.showNoteEditor = false;
      this.noteForm = {
        title: '',
        content: '',
        images: []
      };
    },

    // 删除图片
    deleteImage(index) {
      this.noteForm.images.splice(index, 1);
    },

    // 打开小红书App
    async jumpToXiaohongshuApp() {
      try {
        if (!this.noteForm.title || !this.noteForm.content) {
          throw new Error('请完善笔记内容');
        }

        // 复制文案到剪贴板
        const noteText = `${this.noteForm.title}\n\n${this.noteForm.content}`;
        uni.setClipboardData({
          data: noteText,
          success: () => {
            // 生成小红书跳转 URL
            const xhsUrl = `xhsdiscover://notes/create?title=AI 作品&content=${encodeURIComponent(this.noteForm.content)}`;
            uni.showToast({ title: '跳转小红书...' });

            // 使用 wx.switchTab 跳转到 TabBar 页面
            wx.switchTab({
              url: '/pages/publish/publish', // 确保这里是正确的 TabBar 页面路径
              success: () => {
                console.log('成功跳转到 TabBar 页面');
              },
              fail: (err) => {
                console.error('跳转失败:', err);
              }
            });
          }
        });
      } catch (error) {
        uni.showToast({
          title: error.message,
          icon: 'none'
        });
      }
    },

    async saveChatToDatabase(userMessage, aiMessage) {
      try {
        await uniCloud.callFunction({
          name: 'getRecentChat', // 云函数名称
          data: {
            userId: this.userId,
            chatId: this.chatId,
            messages: [userMessage, aiMessage] // 存储用户和AI的消息
          }
        });
        uni.showToast({
          title: '对话已保存',
          icon: 'success'
        });
      } catch (error) {
        console.error('保存对话失败:', error);
        uni.showToast({
          title: '保存对话失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.chat-container {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.message {
  margin-bottom: 20rpx;
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 20rpx;
  border-radius: 10rpx;
  word-break: break-all;
}

.user-message .message-content {
  background: #007AFF;
  color: #fff;
}

.ai-message .message-content {
  background: #fff;
}

.image-preview {
  padding: 20rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.preview-img {
  width: 150rpx;
  height: 150rpx;
  border-radius: 8rpx;
}

.input-area {
  padding: 20rpx;
  background: #fff;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.upload-btn, .voice-btn, .send-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f0f0;
  border-radius: 30rpx;
}

.text-input {
  flex: 1;
  height: 60rpx;
  background: #f0f0f0;
  border-radius: 30rpx;
  padding: 0 20rpx;
}

.message-actions {
  margin-top: 10rpx;
  text-align: right;
}

.note-editor {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 999;
  padding: 20rpx;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
}

.note-title {
  margin: 20rpx 0;
  padding: 20rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
}

.note-content {
  width: 100%;
  height: 400rpx;
  margin: 20rpx 0;
  padding: 20rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin: 20rpx 0;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
}

.image-item image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0,0,0,0.5);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.note-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.action-btn.upload {
  background: #f0f0f0;
  color: #333;
}

.action-btn.publish {
  background: #fe2c55;
  color: #fff;
}
</style>